package tirateima.gui.console;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.JOptionPane;

public class ConsoleInputStream extends InputStream{

	private Console c;
	private String input = null;
	
	String lastLine;
	int lastKeyCode;
	Object mKeyLock = new Object();
	Object mLineLock = new Object();
	
	public ConsoleInputStream(Console console) {
		this.c = console;
		
		c.addKeyListener(new KeyListener() {

			public void keyTyped(KeyEvent arg0) {
			}
			public void keyReleased(KeyEvent arg0) {
			}
			public void keyPressed(KeyEvent e) {
				System.err.println("keyPressed");
				lastKeyCode = e.getKeyCode();
				if (lastKeyCode == KeyEvent.VK_ENTER) {
					String txt = c.getText();
					int idx = txt.lastIndexOf('\n', c.getCaretPosition() - 1);
					lastLine = txt.substring(idx != -1 ? idx : 0, c.getCaretPosition());
					JOptionPane.showMessageDialog(null, lastLine);
				}
			}
		});
	}


	public String readLine() {
		synchronized(mLineLock) {
			try {
				mLineLock.wait();
			} catch (InterruptedException ex) {
				System.err.println(ex.getMessage());
			}
		}
		return lastLine;
	}
	
	@Override
	public int read() {
		synchronized(mKeyLock) {
			try {
				mKeyLock.wait();
			} catch (InterruptedException ex) {
				System.err.println(ex.getMessage());
			}
		}
		return lastKeyCode;
	}
	
	
	public Object getEntrada() {
		ConsoleInputStream.this.read();
		return null;
	}

}
